package org.wcms.surrounded.web;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.wcms.surrounded.Constants;
import org.wcms.surrounded.web.data.ResponseData;

import com.google.gson.Gson;
import com.google.inject.Inject;
import com.google.inject.Injector;
import com.google.inject.Singleton;

@Singleton
public class SurroundedAjaxServlet extends HttpServlet {

    private static final long serialVersionUID = 1121772714105015169L;

    private final Injector injector;
    private final Gson gson;
    
    @Inject
    public SurroundedAjaxServlet(Injector injector, Gson gson) {
        this.injector = injector;
        this.gson = gson;
    }
    
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        handle(req, resp);
    }
    
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        handle(req, resp);
    }
    
    private void handle(HttpServletRequest req, HttpServletResponse resp) 
            throws ServletException, IOException {
        AjaxHandler handler = getHandler(req);
        ResponseData response = handler.handle(req, resp);
        String responseJson = gson.toJson(response);
        resp.getWriter().println(responseJson);        
    }
    
    private AjaxHandler getHandler(HttpServletRequest request) {
        String command = request.getParameter(Constants.SURROUNDED_AJAX_COMMAND_KEY);
        
        if (Constants.SURROUNDED_AJAX_HIGHSCORES_COMMAND.equalsIgnoreCase(command)) {
            return injector.getInstance(HighScoresAjaxHandler.class);
        } else if (Constants.SURROUNDED_AJAX_ADD_SCORE_COMMAND.equalsIgnoreCase(command)) {
            return injector.getInstance(AddScoreAjaxHandler.class);
        } else {
            return injector.getInstance(BadRequestAjaxHandler.class);
        }
    }
    
}
